let { mysql, config } = require('../qcloud')
let WXBizDataCrypt = require('../utils/WXBizDataCrypt')
let http = require('axios')

// 解密接口
module.exports = async (ctx, next) => {
    const {
        'x-wx-id': openId,
        'x-wx-skey': skey,
        'x-wx-encrypted-data': encryptedData,
        'x-wx-iv': iv,
        'x-wx-proxy-post': proxyPost
    } = ctx.headers

    let appId = config.appId

    try {
        let res = await mysql('cSessionInfo').where({
            open_id: openId,
            skey: skey
        })
        if (res[0] !== undefined) {
            let sessionKey = res[0]['session_key']
            let pc = new WXBizDataCrypt(appId, sessionKey)
            let data = pc.decryptData(encryptedData, iv)
            if (proxyPost.isNotBlank()) {
                let proxyRes = await http({
                    url: `${config.host}/weapp/${proxyPost}`,
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: Object.assign(data, { openId: openId })
                })
                ctx.state.code = proxyRes.data.code
                ctx.state.data = proxyRes.data.data
            } else {
                ctx.state.data = null
                ctx.state.code = 200
            }
        } else {
            ctx.state.data = 'decryptedData fail'
            ctx.state.code = 204
        }
    } catch (error) {
        ctx.state.data = error
        ctx.state.code = 409
    }
}
